package monitor;

import http.HttpUrlConnection;
import model.HTExtractItem;
import monitor.match.BaseMatcher;
import monitor.match.IMatcher;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import utils.TextUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by CatM on 18/1/29.
 */
public class FiveFiveMonitor extends BaseMonitor{

    private static final String FIVE_FIVE_HOST = "https://m.55haitao.com";
    @Override
    public List<HTExtractItem> extractItems() {
        System.out.println("|------------------开始55海淘的爬取-------------------|");
        String response = HttpUrlConnection.getInstance().getString(FIVE_FIVE_HOST, null);
        try {
            ArrayList<HTExtractItem> items = new ArrayList();
            Document doc = Jsoup.parse(response);
            Elements elements = doc.select("#new_deal_ul li");
            for(Element e: elements){
                String path = e.select("a[href]").attr("href");
                String itemName = e.select("img[data-original]").attr("alt");
                String price = e.select(".real-price").html();
                price = TextUtils.isEmpty(price)?"":price.replaceAll(",", "");
                HTExtractItem item = new HTExtractItem(itemName, price, FIVE_FIVE_HOST + path);
                items.add(item);
                System.out.println("itemName="+itemName +"; price="+price+"; url="+FIVE_FIVE_HOST + path);
            }
            return items;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("|------------------结束55海淘的爬取-------------------|");
        return null;
    }

    @Override
    public List<HTExtractItem> find(List<HTExtractItem> extractedItems) {
        IMatcher matcher = new BaseMatcher();
        return matcher.match(extractedItems);
    }
}
